<template>
  <div class="notifications-page">
    <div class="page-header">
      <div class="header-left">
        <router-link to="/" class="back-btn">
          <i class="el-icon-arrow-left"></i>
        </router-link>
        <h1>消息通知</h1>
      </div>
      <div class="header-right">
        <el-button type="text" @click="markAllAsRead" :disabled="!hasUnread">全部标为已读</el-button>
      </div>
    </div>
    
    <div class="tabs-container">
      <el-tabs v-model="activeTab" @tab-click="handleTabChange">
        <el-tab-pane label="全部" name="all">
          <span slot="label">
            全部
            <span v-if="unreadCount > 0" class="tab-badge">{{ unreadCount }}</span>
          </span>
        </el-tab-pane>
        <el-tab-pane label="未读" name="unread">
          <span slot="label">
            未读
            <span v-if="unreadCount > 0" class="tab-badge">{{ unreadCount }}</span>
          </span>
        </el-tab-pane>
        <el-tab-pane label="评论" name="COMMENT"></el-tab-pane>
        <el-tab-pane label="回复" name="REPLY"></el-tab-pane>
      </el-tabs>
    </div>
    
    <div class="notifications-container">
      <div v-if="loading" class="loading-container">
        <el-spinner></el-spinner>
      </div>
      
      <div v-else-if="notifications.length === 0" class="empty-notifications">
        <i class="el-icon-bell empty-icon"></i>
        <p>暂无通知</p>
      </div>
      
      <div v-else class="notification-list">
        <template v-if="activeTab === 'all'">
          <div v-for="(notification, index) in notifications" :key="notification.id">
            <!-- 添加已读/未读消息分割线 -->
            <div 
              v-if="index > 0 && !notifications[index-1].is_read && notification.is_read" 
              class="notification-divider"
            >
              以下是已读消息
            </div>
            
            <div 
              class="notification-item"
              :class="{'unread': !notification.is_read}"
              @click="handleNotificationClick(notification)"
            >
              <div class="notification-avatar">
                <el-avatar 
                  :size="50" 
                  :src="notification.sender_avatar" 
                  @error="handleAvatarError">
                </el-avatar>
              </div>
              <div class="notification-content">
                <div class="notification-sender">{{ notification.notification_type === 'SYSTEM' ? '系统通知' : (notification.sender_name || '未知用户') }}</div>
                <div class="notification-message">{{ getNotificationContent(notification) }}</div>
                <div class="notification-time">{{ formatTime(notification.created_at) }}</div>
              </div>
              <div class="notification-badge-dot" v-if="!notification.is_read"></div>
            </div>
          </div>
        </template>
        
        <template v-else>
          <div 
            v-for="notification in notifications" 
            :key="notification.id" 
            class="notification-item"
            :class="{'unread': !notification.is_read}"
            @click="handleNotificationClick(notification)"
          >
            <div class="notification-avatar">
              <el-avatar 
                :size="50" 
                :src="notification.sender_avatar" 
                @error="handleAvatarError">
              </el-avatar>
            </div>
            <div class="notification-content">
              <div class="notification-sender">{{ notification.notification_type === 'SYSTEM' ? '系统通知' : (notification.sender_name || '未知用户') }}</div>
              <div class="notification-message">{{ getNotificationContent(notification) }}</div>
              <div class="notification-time">{{ formatTime(notification.created_at) }}</div>
            </div>
            <div class="notification-badge-dot" v-if="!notification.is_read"></div>
          </div>
        </template>
        
        <div class="pagination-container" v-if="total > pageSize">
          <el-pagination
            @current-change="handleCurrentChange"
            :current-page.sync="currentPage"
            :page-size="pageSize"
            layout="prev, pager, next"
            :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { 
  getNotifications, 
  getNotificationsByType, 
  getUnreadNotifications, 
  markNotificationAsRead, 
  markAllNotificationsAsRead,
  getActivityIdByCommentId
} from '@/api/api';
import defaultAvatar from "@/assets/images/default-avatar.jpg"; // 导入默认头像

export default {
  name: 'Notifications',
  data() {
    return {
      activeTab: 'all',
      notifications: [],
      loading: false,
      total: 0,
      currentPage: 1,
      pageSize: 10,
      hasUnread: false,
      unreadCount: 0, // 添加未读消息计数
      defaultAvatar: defaultAvatar // 添加默认头像
    };
  },
  methods: {
    checkAvatarUrl(url) {
      if (!url) return this.defaultAvatar;
      return url.replace(/^https:/, 'http:');
    },
    handleAvatarError(e) {
      e.target.src = this.defaultAvatar;
    },
    async fetchNotifications() {
      this.loading = true;
      try {
        let response;
        
        switch (this.activeTab) {
          case 'all':
            response = await getNotifications(this.currentPage, this.pageSize);
            break;
          case 'unread':
            response = await getUnreadNotifications(this.currentPage, this.pageSize);
            break;
          default:
            response = await getNotificationsByType(this.activeTab, this.currentPage, this.pageSize);
            break;
        }
        
        // 更新代码，适配后端返回的数据结构
        let notifications = response.records || [];
        
        // 检查并更新所有通知的头像URL
        notifications.forEach(notification => {
          notification.sender_avatar = this.checkAvatarUrl(notification.sender_avatar);
        });
        
        // 计算未读消息数量
        this.unreadCount = notifications.filter(notification => !notification.is_read).length;
        
        // 对通知列表进行排序
        if (this.activeTab === 'all') {
          // 全部通知：未读消息优先显示，同等已读状态下按时间倒序
          notifications.sort((a, b) => {
            // 首先按照已读状态排序（未读在前）
            if (a.is_read !== b.is_read) {
              return a.is_read ? 1 : -1;
            }
            // 其次按照创建时间排序（新的在前）
            return new Date(b.created_at) - new Date(a.created_at);
          });
        } else if (this.activeTab === 'unread') {
          // 未读通知：按时间倒序
          notifications.sort((a, b) => {
            return new Date(b.created_at) - new Date(a.created_at);
          });
        } else {
          // 特定类型通知：未读消息优先显示，同等已读状态下按时间倒序
          notifications.sort((a, b) => {
            // 首先按照已读状态排序（未读在前）
            if (a.is_read !== b.is_read) {
              return a.is_read ? 1 : -1;
            }
            // 其次按照创建时间排序（新的在前）
            return new Date(b.created_at) - new Date(a.created_at);
          });
        }
        
        this.notifications = notifications;
        console.log('排序后的消息通知列表', this.notifications);
        this.total = response.total || 0;
        this.hasUnread = this.notifications.some(notification => !notification.is_read);
      } catch (error) {
        console.error('获取通知失败:', error);
        this.$message.error('获取通知失败，请稍后重试');
      } finally {
        this.loading = false;
      }
    },
    
    async handleNotificationClick(notification) {
      if (!notification.is_read) {
        try {
          await markNotificationAsRead(notification.id);
          notification.is_read = true;
          this.hasUnread = this.notifications.some(n => !n.is_read);
        } catch (error) {
          console.error('标记通知已读失败:', error);
        }
      }
      
      // 导航到目标内容
      this.navigateToTarget(notification);
    },
    
    navigateToTarget(notification) {
      // 基于resource_type和notification_type决定如何跳转
      const resourceType = notification.resource_type;
      const resourceId = notification.resource_id;
      const notificationType = notification.notification_type;
      console.log('resourceType', resourceType);
      console.log('notificationType', notificationType);

      // 如果是活动类型的资源
      if (resourceType === 'ACTIVITY') {
        // 如果是点赞活动的通知，resourceId就是活动ID，可以直接跳转
        if (notificationType === 'LIKE_ACTIVITY') {
          console.log('检测到点赞活动的通知，活动ID为:', resourceId);
          // 存储activityId到localStorage
          localStorage.setItem("activityId", resourceId);
          
          // 直接跳转到活动详情页
          this.$router.push({ 
            name: 'activity_detail', 
            query: { id: resourceId }
          });
        } 
        // 如果是评论相关的通知，需要获取活动ID
        else {
          this.$message.info('正在获取活动信息...');
          // 显示加载中状态
          const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          console.log('resourceId', resourceId);
          getActivityIdByCommentId(resourceId)
            .then(response => {
              loading.close();
              if (response && response.activity_id) {
                // 存储activityId到localStorage
                console.log('获得返回的活动id是', response.activity_id);
                localStorage.setItem("activityId", response.activity_id);
                
                // 跳转到活动详情页，并携带评论ID
                this.$router.push({ 
                  name: 'activity_detail', 
                  query: { id: response.activity_id }
                });
              } else {
                this.$message.warning('无法找到对应的活动信息');
              }
            })
            .catch(error => {
              loading.close();
              console.error('获取评论活动ID失败:', error);
              this.$message.error('获取活动信息失败，请稍后重试');
            });
        }
      } 
      // 如果是评论类型的资源
      else if (resourceType === 'COMMENT') {
        
        let activityId = null;
        
        // 如果还是没有找到activity_id，调用新的API接口获取
        if (!activityId) {
          this.$message.info('正在获取活动信息...');
          // 显示加载中状态
          const loading = this.$loading({
            lock: true,
            text: '加载中',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          console.log('resourceId', resourceId);
          getActivityIdByCommentId(resourceId)
            .then(response => {
              loading.close();
              if (response && response.activity_id) {
                // 存储activityId到localStorage
                console.log('获得返回的活动id是', response.activity_id);
                localStorage.setItem("activityId", response.activity_id);
                
                // 跳转到活动详情页，并携带评论ID
                this.$router.push({ 
                  name: 'activity_detail', 
                  query: { id: response.activity_id }
                });
              } else {
                this.$message.warning('无法找到对应的活动信息');
              }
            })
            .catch(error => {
              loading.close();
              console.error('获取评论活动ID失败:', error);
              this.$message.error('获取活动信息失败，请稍后重试');
            });
        } else {
          // 如果已经有activity_id，直接跳转
          localStorage.setItem("activityId", activityId);
          
          this.$router.push({ 
            name: 'activity_detail', 
            query: { id: activityId }
          });
        }
      }
      // 系统通知
      else if (notificationType === 'SYSTEM' || resourceType === 'SYSTEM') {
        // 系统通知通常不需要跳转
        this.$message.info('这是一条系统通知');
      }
      // 处理未知资源类型
      else {
        console.warn('未知的资源类型:', resourceType, '通知类型:', notificationType);
        // 尝试根据通知类型进行兜底处理
        const typeActionMap = {
          'COMMENT': '评论',
          'REPLY': '回复',
          'LIKE_ACTIVITY': '点赞活动',
          'LIKE_COMMENT': '点赞评论',
          'MENTION': '提及'
        };
        const actionText = typeActionMap[notificationType] || '通知';
        this.$message.info(`收到${actionText}通知，但无法确定跳转目标`);
      }
    },
    
    async markAllAsRead() {
      try {
        await markAllNotificationsAsRead();
        // 更新已读状态
        this.notifications.forEach(notification => {
          notification.is_read = true;
        });
        // 更新未读状态和计数
        this.hasUnread = false;
        this.unreadCount = 0;
        this.$message.success('已全部标记为已读');
        
        // 如果在全部标签页，重新排序列表（因为排序规则依赖已读状态）
        if (this.activeTab === 'all') {
          this.notifications.sort((a, b) => {
            return new Date(b.created_at) - new Date(a.created_at);
          });
        }
      } catch (error) {
        console.error('标记已读失败:', error);
        this.$message.error('操作失败，请稍后重试');
      }
    },
    
    handleTabChange() {
      this.currentPage = 1; // 切换标签时重置页码
      this.fetchNotifications();
    },
    
    handleCurrentChange(page) {
      this.currentPage = page;
      this.fetchNotifications();
    },
    
    formatTime(timestamp) {
      if (!timestamp) return '';
      
      const now = new Date();
      const date = new Date(timestamp);
      const diff = now - date;
      
      // 计算时间差
      const minutes = Math.floor(diff / 1000 / 60);
      const hours = Math.floor(minutes / 60);
      const days = Math.floor(hours / 24);
      
      // 如果小于1分钟
      if (minutes < 1) {
        return '刚刚';
      }
      // 如果小于1小时
      if (minutes < 60) {
        return `${minutes}分钟前`;
      }
      // 如果小于24小时
      if (hours < 24) {
        return `${hours}小时前`;
      }
      // 如果小于7天
      if (days < 7) {
        return `${days}天前`;
      }
      
      // 格式化日期显示
      const year = date.getFullYear();
      const month = (date.getMonth() + 1).toString().padStart(2, '0');
      const day = date.getDate().toString().padStart(2, '0');
      
      if (year === now.getFullYear()) {
        return `${month}月${day}日`;
      }
      
      return `${year}年${month}月${day}日`;
    },
    
    // 添加头像加载错误处理方法
    handleAvatarError(e) {
      e.target.src = this.defaultAvatar;
    },
    
    // 添加解析通知内容的方法
    getNotificationContent(notification) {
      // 首先尝试从content字段获取内容
      if (notification.content) {
        return notification.content;
      }
      
      // 如果有message字段，使用message字段
      if (notification.message) {
        return notification.message;
      }
      
      // 尝试解析metadata字段
      if (notification.metadata) {
        try {
          const metadataObj = JSON.parse(notification.metadata);
          if (metadataObj.content) {
            // 去除可能的多余换行符
            return metadataObj.content.trim();
          }
          if (metadataObj.message) {
            return metadataObj.message.trim();
          }
        } catch (error) {
          console.error('解析metadata失败:', error);
        }
      }
      
      // 如果以上都失败，根据通知类型返回默认文本
      const typeTextMap = {
        'COMMENT': '收到了新评论',
        'REPLY': '收到了回复',
        'LIKE_ACTIVITY': '点赞了你的活动',
        'LIKE_COMMENT': '点赞了你的评论',
        'MENTION': '在帖子中提到了你',
        'SYSTEM': '系统通知'
      };
      
      return typeTextMap[notification.notification_type] || '收到一条新通知';
    }
  },
  async mounted() {
    // 获取通知列表
    await this.fetchNotifications();
    
    // 如果有未读通知，自动标记为已读
    if (this.hasUnread) {
      await this.markAllAsRead();
    }
  }
};
</script>

<style scoped>
.notifications-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
}

.back-btn {
  margin-right: 15px;
  font-size: 20px;
  color: #606266;
  text-decoration: none;
}

h1 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.tabs-container {
  margin-bottom: 15px;
}

.loading-container {
  display: flex;
  justify-content: center;
  padding: 30px 0;
}

.empty-notifications {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  color: #909399;
}

.empty-icon {
  font-size: 50px;
  color: #c0c4cc;
  margin-bottom: 10px;
}

.notification-list {
  border-radius: 4px;
}

.notification-item {
  display: flex;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  position: relative;
  cursor: pointer;
  transition: background-color 0.3s;
  align-items: flex-start;
}

.notification-item:hover {
  background-color: #f5f7fa;
}

.notification-item.unread {
  background-color: #ecf5ff;
  border-left: 4px solid #409EFF;
}

.notification-avatar {
  margin-right: 15px;
}

.notification-content {
  flex: 1;
}

.notification-sender {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 4px;
}

.notification-message {
  font-size: 14px;
  color: #303133;
  line-height: 1.5;
}

.notification-time {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.notification-badge-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #f56c6c;
  position: absolute;
  right: 15px;
  top: 15px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 10px 0;
}

@media screen and (max-width: 768px) {
  .notifications-page {
    padding: 15px;
  }
  
  .page-header {
    margin-bottom: 15px;
  }
  
  .notification-avatar {
    margin-right: 10px;
  }
  
  h1 {
    font-size: 16px;
  }
}

/* 添加已读/未读消息分割线样式 */
.notification-divider {
  text-align: center;
  color: #909399;
  font-size: 14px;
  padding: 10px 0;
  margin: 5px 0;
  background-color: #f5f7fa;
  border-top: 1px solid #ebeef5;
  border-bottom: 1px solid #ebeef5;
}

/* 添加标签上的未读徽章样式 */
.tab-badge {
  display: inline-block;
  background-color: #f56c6c;
  border-radius: 10px;
  color: white;
  font-size: 12px;
  height: 16px;
  line-height: 16px;
  padding: 0 6px;
  margin-left: 4px;
  vertical-align: text-top;
  min-width: 16px;
  text-align: center;
}
</style>